<script setup lang="ts">
import { ref } from 'vue';
import { asyncRoutes } from '@/router';
import { useDuty, useSetDuty } from '@/api/systemRole';
import type { RouteRecordRaw } from 'vue-router';
import { handleMessage } from '@/utils/globalEvent';

const treeRef = ref();
const loading = ref(true);
// 职责树
const treeValue = ref<any>([]);
// 职责树是否可操作
const treeEditState = ref(true);
// 当前展示id
const treeId = ref<number | null>(null);

// 设置权限树
const setPermissions = (routes: RouteRecordRaw[]): [] => {
	const tree: any = [];
	// 循环动态
	routes.map(route => {
		const item: any = { ...route };
		// 若是有children
		if (item.children) item.children = setPermissions(item.children);
		// 没有 title 值则停止
		if (!item.meta.title) return;
		tree.push({
			id: item.name,
			label: item.meta.title,
			disabled: !treeEditState.value,
			children: item.children || null,
		});
	});
	return tree;
};
treeValue.value = setPermissions(asyncRoutes);

// 获取拥有职责
const postDuty = async (id: number) => {
	if (!loading.value) loading.value = true;
	try {
		const result = await useDuty({ id });
		if (!result) return;
		treeId.value = id;
		// 默认选中节点
		treeRef.value?.setCheckedKeys(result.duty);
		// 是否可操作
		if (treeEditState.value !== result.edit) {
			treeEditState.value = result.edit;
			treeValue.value = setPermissions(asyncRoutes);
		}
	} catch (error) {
		throw new Error('获取职责未知异常,请联系开发人员');
	} finally {
		loading.value = false;
	}
};

// 修改职责
const clickSubmit = async () => {
	// loading.value = true;
	// 半选中（父节点）与选中节点集合
	if (!treeId.value) return;
	loading.value = true;
	const params: any = {};
	// 选中节点
	treeRef.value.getCheckedKeys().forEach((item: string) => {
		params[item] = 1;
	});
	// 半选中节点
	treeRef.value.getHalfCheckedKeys().forEach((item: string) => {
		params[item] = 2;
	});
	params.id = treeId.value;
	try {
		const result = await useSetDuty(params);
		if (!result) return;
		handleMessage(result);
	} catch (error) {
		throw new Error('设置职责未知异常,请联系开发人员');
	} finally {
		postDuty(treeId.value);
	}
};

defineExpose({
	postDuty,
});
</script>

<template>
	<div v-part-loading="loading" class="duty">
		<el-tree ref="treeRef" :data="treeValue" node-key="id" default-expand-all show-checkbox>
			<template #default="{ node }">
				{{ $t(node.label) }}
			</template>
		</el-tree>
		<el-button v-show="treeEditState" @click="clickSubmit">修改</el-button>
	</div>
</template>

<style lang="less" scoped>
@import url('./index.less');
</style>
